<template>
  <div class="home">
    <van-nav-bar title="智能猫窝" left-arrow @click-left="onClickLeft" />
    <div class="home-content">
      <p class="home-content-area-text">基本信息</p>
      <transition-group tag="ul" class="home-content-info">
        <li
          class="home-content-info-item"
          @click="onDevices(item, index)"
          v-for="(item, index) in infoData"
          :key="item"
        >
          <div class="home-content-info-item-title">
            <p class="home-content-info-item-title-name">{{ item.name }}</p>
          </div>
          <p class="home-content-info-item-data" :style="{ color: item.color }">
            {{ item.data }}
          </p>
        </li>
      </transition-group>
      <p class="home-content-area-text">设备控制</p>
      <div class="home-content-echarts" style="height: 400px">
        <van-cell
          center
          size="large"
          :label="deviceData.modeState === true ? '自动' : '手动'"
          title="控制模式"
        >
          <template #right-icon>
            <van-switch
              v-model="deviceData.modeState"
              :loading="deviceData.modeload"
              @change="onmodeChange(deviceData)"
              size="25"
            />
          </template>
        </van-cell>
        <van-cell
          center
          size="large"
          :label="deviceData.ledState === true ? '开启' : '关闭'"
          title="灯光开关"
        >
          <template #right-icon>
            <van-switch
              v-model="deviceData.ledState"
              :loading="deviceData.ledload"
              @change="onledChange(deviceData)"
              :disabled="deviceData.modeState"
              size="24"
            />
          </template>
        </van-cell>
        <van-cell
          center
          size="large"
          :label="deviceData.ledSet + 'Lux'"
          title="灯光开启阈值"
        >
          <template #right-icon>
            <van-stepper
              v-model="deviceData.ledSet"
              step="5"
              min="0"
              async-change
              @change="onledSet"
            />
            <!-- <van-switch v-model="deviceData.relayState" :loading="deviceData.relayload" @change="onrelayChange(deviceData)" size="24" /> -->
          </template>
        </van-cell>
        <van-cell
          center
          size="large"
          :label="deviceData.relayState === true ? '开启' : '关闭'"
          title="空调开关"
        >
          <template #right-icon>
            <van-switch
              v-model="deviceData.relayState"
              :loading="deviceData.relayload"
              @change="onrelayChange(deviceData)"
              :disabled="deviceData.modeState"
              size="24"
            />
          </template>
        </van-cell>
        <van-cell
          center
          size="large"
          :label="deviceData.relaySet + '°C'"
          title="空调开启阈值"
        >
          <template #right-icon>
            <van-stepper
              v-model="deviceData.relaySet"
              step="1"
              min="16"
              max="30"
              async-change
              @change="onrelaySet"
            />
            <!-- <van-switch v-model="deviceData.relayState" :loading="deviceData.relayload" @change="onrelayChange(deviceData)" size="24" /> -->
          </template>
        </van-cell>

        <!-- <van-cell
          center
          size="large"
          :label="deviceData.relay2State === true ? '开启' : '关闭'"
          title="风扇开关"
        >
          <template #right-icon>
            <van-switch
              v-model="deviceData.relay2State"
              :loading="deviceData.relay2load"
              @change="onrelay2Change(deviceData)"
              size="24"
            />
          </template>
        </van-cell> -->
      </div>
      <p class="home-content-area-text">图表数据</p>
      <div class="home-content-myecharts">
        <div
          id="echartspeed"
          style="margin: 10px; width: auto; height: 30vh"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import * as echarts from "echarts";
var send = {};
export default {
  components: {},

  mounted: function () {
    this.mqttMsg();
    this.myEcharts();
  },
  data: function () {
    return {
      tempdata:[],
      tempdate:[],
      deviceData: {
        modeload: false,
        ledload: false,
        relayload: false,
        relay2load: false,
        ledSet: localStorage.getItem("Dorm_ledSet"),
        relaySet: localStorage.getItem("Dorm_relaySet"),
        modeState: false,
        ledState: false,
        relayState: "",
        relay2State: "",
      },
      tableData: [],
      infoData: [
        {
          // Icon: require('@img/ADD1.svg'),
          name: "环境温度",
          data: "--",
        },
        {
          // Icon: require('@img/ADD1.svg'),
          name: "环境湿度",
          data: "--",
        },
        {
          // Icon: require('@img/ADD1.svg'),
          name: "光照度",
          data: "--",
        }
      ],
    };
  },
  activated: function () {
    // 在 keepAlive 被激活的时候，调用指定加载页面组件的方法
    // this.LoginCheck();
    // console.log(this.$store.state.username)
  },
  methods: {
    formatDate(params) {
      let date = params;
      let formatStr = "HH:mm:ss";
      // 传入日期字符串 - 转成时间戳 - 转成标准时间
      let timeStamp = params.getTime();
      console.log(timeStamp);
      date = new Date(timeStamp);
      formatStr = formatStr.replace(
        new RegExp("yyyy"),
        `${date.getFullYear()}`
      );
      const month = date.getMonth() + 1;
      formatStr = formatStr.replace(
        new RegExp("MM"),
        `${month > 9 ? month : "0" + month}`
      );
      const day = date.getDate();
      formatStr = formatStr.replace(
        new RegExp("dd"),
        `${day > 9 ? day : "0" + day}`
      );
      const hour = date.getHours();
      formatStr = formatStr.replace(
        new RegExp("HH"),
        `${hour > 9 ? hour : "0" + hour}`
      );
      const min = date.getMinutes();
      formatStr = formatStr.replace(
        new RegExp("mm"),
        `${min > 9 ? min : "0" + min}`
      );
      const sec = date.getSeconds();
      formatStr = formatStr.replace(
        new RegExp("ss"),
        `${sec > 9 ? sec : "0" + sec}`
      );
      return formatStr;
    },
    myEcharts() {
      // 基于准备好的dom，初始化echarts实例
      this.speedChart = echarts.init(document.getElementById("echartspeed"));
      this.speedChart.setOption({
        tooltip: {
          trigger: "axis",
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        title: {
          left: "center",
          text: "温度变化记录",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.beatdate,
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          min: -20,
          max: 50,
        },
        series: [
          {
            name: "温度",
            type: "line",
            symbol: "none",
            sampling: "lttb",
            itemStyle: {
              color: "rgb(255, 70, 131)",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgb(255, 158, 68)",
                },
                {
                  offset: 1,
                  color: "rgb(255, 70, 131)",
                },
              ]),
            },
            data: this.tempdata,
          },
        ],
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },

    onmodeChange(res) {
      this.deviceData.modeState = res.modeState;
      this.deviceData.modeload = true;
      send = {};
      send["ModeFlag"] = res.modeState === true ? "1" : "0";
      this.$mqtt.publish(this.$route.params.sub, send);
    },
    onledChange(res) {
      console.log(res)
      this.deviceData.ledload = true;
      send = {};
      send["Led"] = res.ledState === true ? "1" : "0";
      this.$mqtt.publish(this.$route.params.sub, send);
    },
    onrelayChange(res) {
      this.deviceData.relayState = res.relayState;
      this.deviceData.relayload = true;
      send = {};
      send["Fan"] = res.relayState === true ? "1" : "0";
      console.log(send)
      this.$mqtt.publish(this.$route.params.sub, send);
    },
    onrelay2Change(res) {
      this.deviceData.relay2State = res.relay2State;
      this.deviceData.relay2load = true;
      send = {};
      send["R2"] = res.relay2State === true ? "1" : "0";
      this.$mqtt.publish(this.$route.params.sub, send);
    },
    onledSet(value) {
      localStorage.setItem("Dorm_ledSet",value)
      var send = {};
      send["LuxSet"] = value.toString()
      this.$mqtt.publish(this.$route.params.sub, send);
      Toast.loading({ forbidClick: true });
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        Toast.clear();
      }, 500);
      
    },
    onrelaySet(value) {
      localStorage.setItem("Dorm_relaySet",value)
      var send = {};
      send["FanSet"] = value.toString()
      this.$mqtt.publish(this.$route.params.sub, send);
      Toast.loading({ forbidClick: true });
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        Toast.clear();
      }, 500);
      
    },
    mqttMsg() {
      this.$mqtt.message(this.$route.params.pub, (topic, source) => {
        console.log("message: ", JSON.parse(source.toString()));
        try {
          this.res = JSON.parse(source.toString());
          // 更新非控制部分的状态信息
          this.infoData[0].data = this.res.Temp.toFixed(2) + "°C";
          this.infoData[1].data = this.res.Humi.toFixed(2) + "%";
          this.infoData[2].data = this.res.Lux + "%";
          // this.infoData[2].data = this.res.LU + "Lux";
          // this.infoData[3].data = this.res.FI === 1 ? "正常" : "警报";
          // this.infoData[3].color = this.res.FI === 1 ? "green" : "red";
           this.deviceData.ledSet = this.res.LuxSet
           this.deviceData.relaySet = this.res.FanSet


          this.tempdate.push(this.formatDate(new Date()));
          this.tempdata.push((this.infoData[0].data = this.res.Temp.toFixed(2)))
          this.speedChart.setOption({
            xAxis: {
              data: this.tempdate,
            },
            series: [
              {
                data: this.tempdata,
              },
            ],
          });

          if (this.deviceData.modeload) {
            if (
              this.deviceData.modeState === (this.res.ModeFlag === 1 ? true : false)
            ) {
              this.deviceData.modeload = false;
              Toast.success("模式设定成功");
            } else {
              console.log(this.param);
              var send = {};
              send["ModeFlag"] = this.deviceData.modeState === true ? "1" : "0";
              this.$mqtt.publish(this.$route.params.sub, send);
            }
          } else {
            this.deviceData.modeState = this.res.ModeFlag === 1 ? true : false;
            console.log(this.deviceData.modeState);
          }


          if (this.deviceData.ledload) {
            if (
              this.deviceData.ledState === (this.res.Led === 1 ? true : false)
            ) {
              this.deviceData.ledload = false;
              Toast.success("设定成功");
            } else {
              // console.log(this.param);
              send = {};
              send["Led"] = this.deviceData.ledState === true ? "1" : "0";
              this.$mqtt.publish(this.$route.params.sub, send);
            }
          } else {
            this.deviceData.ledState = this.res.Led === 1 ? true : false;
          }


          if (this.deviceData.relayload) {
            if (
              this.deviceData.relayState === (this.res.Fan === 1 ? true : false)
            ) {
              this.deviceData.relayload = false;
              Toast.success("设定成功");
            } else {
              send = {};
              send["Fan"] = this.deviceData.relayState === true ? "1" : "0";
              this.$mqtt.publish(this.$route.params.sub, send);
            }
          } else {
            this.deviceData.relayState = this.res.Fan === 1 ? true : false;
          }


          // if (this.deviceData.relay2load) {
          //   if (
          //     this.deviceData.relay2State === (this.res.R2 === 1 ? true : false)
          //   ) {
          //     this.deviceData.relay2load = false;
          //     Toast.success("设定成功");
          //   } else {
          //     send = {};
          //     send["R2"] = this.deviceData.relay2State === true ? "1" : "0";
          //     this.$mqtt.publish(this.$route.params.sub, send);
          //   }
          // } else {
          //   this.deviceData.relay2State = this.res.R2 === 1 ? true : false;
          // }



        } catch (err) {
          console.log(err.message);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
  transform: translateX(100px);
}

.v-enter-active,
.v-leave-to {
  transition: all 0.6s ease;
}

/* v-move 和 v-leave-to 配合使用，能够实现列表后续的元素，逐渐飘上来的效果 */
.v-move {
  transition: all 0.6s ease;
}

.v-leave-to {
  position: absolute;
}
.home {
  width: 100%;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-flow: column;
  position: absolute;
  &-content {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: left;
    transition: 0.3s;
    overflow-x: hidden;
    &-myecharts {
      transition: 0.5s;
      text-align: center;
      margin: 0 16px 15px;
      //padding: 0 16px 15px;
      border-radius: 20px 20px 20px 20px;
      // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
      width: auto;
      height: 40vh;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: left;
      background-color: rgba(255, 255, 255, 0.9);
      background-attachment: fixed;
    }
    &-echarts {
      margin: 0 16px 0px;
      width: auto;
      display: flex;
      position: relative;
      flex-direction: column;
      justify-content: left;
      background-attachment: fixed;
    }
    &-control {
      border-radius: 20px;
      margin-top: 0px;
      margin-left: 20px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
    &-area {
      &-text {
        margin-left: 20px;
        font-size: 5vw;
        color: white;
        font-weight: 900;
      }
    }
    &-text {
      margin: px2rem(20);
      font-size: px2rem(30);
      color: white;
      font-weight: 600;
      margin-bottom: px2rem(30);
    }
    &-shebei {
      margin-left: px2rem(20);
      margin-bottom: px2rem(5);
      font-size: px2rem(14);
      color: white;
      font-weight: 400;
    }
    &-info {
      transition: 0.5s;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 16px 0 16px;

      &-item {
        transition: 0.5s;
        margin: 5px;
        text-align: center;
        padding: 5px;
        border-radius: 20px 20px 20px 20px;
        // box-shadow: 0 0 16px 0 rgba(0, 0, 0, 0.3);
        width: calc(50% - 20px);
        // height: calc(50% - 10px);
        display: flex;
        position: relative;
        flex-direction: column;
        justify-content: left;
        background-color: rgba(255, 255, 255, 0.9);
        background-attachment: fixed;
        &-title {
          display: flex;
          flex-direction: row;
          align-items: center;

          &-name {
            margin: auto;
            transition: 0.5s;
            text-align: left;
            color: black;
            //margin-top: 0;
            font-size: 4vw;
          }
        }

        &-data {
          transition: 0.5s;
          // text-align: right;
          color: black;
          margin: auto;
          font-size: 9vw;
          font-weight: 500;
        }
      }
    }
  }
}
.custom-button {
  width: auto;
  padding: 5px 10px;
  color: #fff;
  font-size: 4vw;
  line-height: 5vw;
  text-align: center;
  background-color: #0aadee;
  border-radius: 20px;
}
.van-cell {
  margin: 0 0 10px 0;
  width: auto;
  border-radius: 10px;
  
}
</style>
